<template>
  <el-dialog
    title="用户注册"
    :visible.sync="isShow"
    width="600px"
    class="register"
    center
    :show-close="false"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    @closed="updateImgUrl()"
  >
    <!-- 头标题 -->
    <template #title>
      <div class="title">用户注册</div>
    </template>
    <!-- 底部 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="isShow=false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
    <!-- 表单 -->
    <el-form
      ref="form"
      :model="form"
      label-position="left"
      label-width="60px"
      :rules="rules"
    >
      <el-form-item label="头像" class="upload-avatar" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="form.avatar"
            :src="baseUrl + '/' + form.avatar"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code">
        <el-row type="flex" justify="space-between">
          <el-col :span="16">
            <el-input v-model="form.code"> </el-input>
          </el-col>
          <el-col :span="7">
            <img
              :src="imageCodeUrl"
              @click="updateImgUrl"
              class="img-code"
              alt=""
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row type="flex" justify="space-between">
          <el-col :span="16">
            <el-input v-model="form.rcode"> </el-input>
          </el-col>
          <el-col :span="7">
            <el-button
              :class="{ smsCode: isTimeTip }"
              @click="getSMSCode"
              :disabled="isSendSMS"
              >{{ tipMsg }}</el-button
            >
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>


<script>
import { getRegisterSMSCode, registerPost } from "@/api/register.js";
export default {

  watch: {
    isShow (newVal)  {
      if (!newVal) {
        this.$refs.form.resetFields();
        this.form.num = 0;
      } else {
        // this.updateImgUrl();
      }
    },
  },
  data() {
    const validate = (rule, value, callback, reg, reqMsg, regMsg) => {
      if (value.trim() === "") return callback(new Error(reqMsg));
      reg.test(value) ? callback() : callback(new Error(regMsg));
    };
    const validatePhone = (rule, value, callback) => {
      const _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      validate(
        rule,
        value,
        callback,
        _reg,
        "请输入手机号",
        "请输入正确的手机号"
      );
    };
    const validatePass = (rule, value, callback) => {
      const _reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/;
      validate(
        rule,
        value,
        callback,
        _reg,
        "请输入密码",
        "请输入字母和数字组成的8到16的密码,不能是纯数值和纯字母"
      );
    };
    const validateEmail = (rule, value, callback) => {
      const _reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      validate(rule, value, callback, _reg, "请输入邮箱", "请输入正确的邮箱");
    };
    const validateUsername = (rule, value, callback) => {
      callback();
    };
    const validateCode = (rule, value, callback) => {
      if (value.trim().length === 0)
        return callback(new Error("请输入图片验证码"));
      if (value.trim().length !== 4)
        return callback(new Error("图片验证码格式有误"));
      callback();
    };
    const validateRcode = (rule, value, callback) => {
      if (value.trim().length === 0)
        return callback(new Error("请输入短信验证码"));
      if (value.trim().length !== 4)
        return callback(new Error("短信验证码格式有误"));
      callback();
    };
    return {
      tipMsg: "获取用户验证码",
      isTimeTip: false,
      isSendSMS: false,
      isShow: false,
      form: {
        avatar: "", //是	string	头像地址
        username: "", // 是	string	用户名
        email: "", // 是	string	邮箱
        phone: "", // 是	string	手机号
        password: "", // 是	string	密码
        code: "",
        rcode: "", // 是	string	验证码
      },
      rules: {
        avatar: [{ required: true, message: "请上传头像", trigger: "change" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { validator: validateUsername, trigger: "blur" },
        ], // 是	string	用户名
        email: [{ required: true, validator: validateEmail, trigger: "blur" }], // 是	string	邮箱
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        code: [
          { validator: validateCode, trigger: "blur" },
          // { validator: validateErr, trigger: "click"},
        ],
        rcode: [
          { validator: validateRcode, trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (this.form?.userRcode && value != this.form.userRcode) {
                return callback(new Error("短信验证码错误"));
              }
              callback();
            },
            trigger: "send",
          },
        ], // 是	string	验证码
      },
      //   基地址
      baseUrl: process.env.VUE_APP_URL,
      imageCodeUrl: process.env.VUE_APP_URL + "/captcha?type=sendsms",
    };
  },
  methods: {
    getSMSCode() {
      if (!this.isSendSMS) {
        this.isSendSMS = true;
        const validateFieldArr = ["phone", "code"];
        validateFieldArr.num = 0;
        this.$refs.form.validateField(validateFieldArr, (errorMssage) => {
          if (!errorMssage) {
            validateFieldArr.num += 1;
          }
        });

        if (validateFieldArr.num === validateFieldArr.length) {
          getRegisterSMSCode({
            phone: this.form.phone,
            code: this.form.code,
          }).then((res) => {
            if (res.data.data.length === 0) {
              const filed =
                res.data.message === "验证码错误"
                  ? validateFieldArr[1]
                  : validateFieldArr[0];
              // 短信验证码错误时,添加一个临时新的验证方法
              this.rules[filed].push({
                validator: (rule, value, callback) => {
                  callback(new Error(res.data.message));
                },
              });
              // 触发验证
              this.$refs.form.validateField(filed);
              // 删除临时验证
              this.rules[filed].length = 1;
              // 刷新图形验证码
              this.updateImgUrl();
              this.isSendSMS = false;
            } else {
              this.form.userRcode = res.data.data.captcha;
              this.$message.success(res.data.data.captcha + "");
              this.form.num = 59;
              this.tipMsg = this.form.num + "秒";
              this.isTimeTip = true;
              const timerId = setInterval(() => {
                if (this.form.num <= 0) {
                  this.tipMsg = "获取用户验证码";
                  clearInterval(timerId);
                  this.isSendSMS = false;
                  this.isTimeTip = false;
                } else {
                  this.form.num--;
                  this.tipMsg = this.form.num + "秒";
                }
              }, 1000);
            }
          });
        } else {
          this.isSendSMS = false;
        }
      }
    },
    updateImgUrl() {
      this.imageCodeUrl =
        process.env.VUE_APP_URL +
        "/captcha?type=sendsms" +
        "&tt=" +
        new Date().getTime();
    },
    handleAvatarSuccess(res) {
      // 将上传成功后的图片路径赋值给表单图片属性
      this.form.avatar = res.data.file_path;
      // 校验图片字段
      this.$refs.form.validateField(["avatar"]);
      // console.log(res);
    },
    beforeAvatarUpload(file) {
      const isJPG_PNG_JPEG = ["image/jpeg", "image/png", "image/jpg"].includes(
        file.type
      );
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG_PNG_JPEG) {
        this.$message.error("上传头像图片只能是 JPG,PNG,JPEG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG_PNG_JPEG && isLt2M;
    },
    submit() {
      this.$refs.form.validate((result) => {
        if (result) {
          registerPost(this.form)
            .then((res) => {
              if (res.data.data.length === 0) {
                const errMsgs = {
                  用户名已存在: "username",
                  邮箱已存在: "email",
                  手机号重复: "phone",
                };
                const filed = errMsgs[res.data.message];
                // const filed = res.data.message === "用户名已存在" ? "username" : res.data.message === "手机号重复" ? 'phone': 'email';
                // 短信验证码错误时,添加一个临时新的验证方法
                this.rules[filed].push({
                  validator: (rule, value, callback) => {
                    callback(new Error(res.data.message));
                  },
                });
                // 触发验证
                this.$refs.form.validateField(filed);
                // 删除临时验证
                this.rules[filed].length = 1;
              } else {
                this.$message.success("注册成功, 请登录");
                this.isShow = false;
              }
            })
            .catch((error) => {
              this.$message.error(error);
            });
        } else {
          this.$message.error("验证失败");
        }
      });
    },
  },
};
</script>

<style lang="less">
.register {
  margin-top: -70px;
  .title {
    height: 53px;
    width: 600px;
    background: linear-gradient(to right, #01c4fa, #1294fa);
    line-height: 53px;
    color: #fff;

    text-align: center;
  }
  .el-dialog__header {
    padding: 0;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-left: -60px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .upload-avatar {
    text-align: center;
  }
  .img-code {
    height: 40px;
    width: 100%;
    vertical-align: top;
  }
  .smsCode {
    width: 100%;
    color: rgb(255, 60, 0);
  }
}
</style>